﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using BS_2.Class;
using Sunny.UI;
using ESRI.ArcGIS.Analyst3D;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Catalog;
using ESRI.ArcGIS.CatalogUI;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.SystemUI;
using Kitware.VTK;
using BS_2.VTKClass;
using System.Threading;
using ESRI.ArcGIS.Display;
using CCWin;
using ESRI.ArcGIS.DataSourcesRaster;
using ESRI.ArcGIS.DataSourcesGDB;
using ESRI.ArcGIS.Output;

namespace BS_2
{
    public partial class Form1 : CCWin.Skin_DevExpress
    {
        //VTK
        protected vtkOrientationMarkerWidget marker;

        bool isQUJian = false;//是否启用显示区间

        public float[] varlimitData = new float[2];//用户定义的颜色显示的区间

        public int returnNum = 0;

        ZoneData zoneData;
        ContourZone contourZoneChange;

        public string varNow;
        //VTK

        //
        public ILayer pMoveLayer;
        public int toIndex;
        //更换图层

        //剖面图
        public string dicpath;
        //


        private string sMapUnits = "未知单位";
        private IPoint pMovePt = null;
        private ILayer m_layer;
        private string LayerName;
        //public MemoryStream ms;
        public Form1()
        {
            Dictionary<string, int> triangleFace = new Dictionary<string, int>();
            for (int i = 0; i < 5000000; i++)
            {
                triangleFace.Add(i + "", i);
            }
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.axMapControl1.Map.Name = "地质数据资料图层";
            
            /*vtkRenderer renderer1 = vtkRenderer.New();
            renderer1.SetBackground(255, 255, 255);
            vtkRenderWindow renderWindow = RWControl.RenderWindow;
            renderWindow.AddRenderer(renderer1);*/
            this.RWControl.Hide();
            axTOCControl1.SetBuddyControl(axMapControl1.Object);
            //axToolbarControl1.SetBuddyControl(axMapControl1.Object);
            //TreeViewShowNodeProjectItem();
            TreeViewShowNodeProjectItem();
            //TreeViewShowNodeDataSet(14);
            //vtkShow("D:\\合工大learn文档\\毕业设计\\毕设\\测试数据\\三维数据\\筛选后txt\\断层.txt");

            //vtkshow2("D:\\QQ文件\\陈玉恒_4_6\\VtkSample\\VtkSample\\bin\\x64\\Debug\\fulldata0.csv");
        }

        public void TreeViewShowNodeProjectItem()
        {
            //this.treeView1.SelectedNode.ImageIndex = 5;
            string sql = "select prjname from project";
            DataTable dt = DataAccess.Get_DataTable(sql, "prj");
            for(int i = 0; i < dt.Rows.Count; i++)
            {
                treeView1.Nodes.Add(dt.Rows[i][0].ToString());
                treeView1.ImageIndex = 5;
            }
            
            
        }
        public void TreeViewShowNodeDataSet(int prjcode)
        {
            
            TreeNode photoNode=null;
            TreeNode txtNode=null;
            TreeNode VectorNode=null;
            TreeNode ThreeDNode=null;
            TreeNode TifNode = null;
            TreeNode SectionalPicNode = null;
            /*string sql1 = "select prjname,prjdataset from project where prjcode ="+prjcode;
            DataTable dt1 = DataAccess.Get_DataTable(sql1, "prj");
            TreeNode f = treeView1.Nodes.Add(dt1.Rows[0][0].ToString());
            f.ImageIndex = 5;
            string[] datasetitem = dt1.Rows[0][1].ToString().Split(",");
            for(int i = 0; i < datasetitem.Length; i++)
            {
                if(datasetitem[i] == "图片")
                {
                    photoNode = f.Nodes.Add(datasetitem[i]);
                    photoNode.ImageIndex = 0;
                }
                if (datasetitem[i] == "文档")
                {
                    txtNode = f.Nodes.Add(datasetitem[i]);
                    txtNode.ImageIndex = 0;
                }
                if (datasetitem[i] == "矢量数据")
                {
                    VectorNode = f.Nodes.Add(datasetitem[i]);
                    VectorNode.ImageIndex = 0;
                }
                if (datasetitem[i] == "三维模型")
                {
                    ThreeDNode = f.Nodes.Add(datasetitem[i]);
                    ThreeDNode.ImageIndex = 0;
                }

                

            }
            f.ExpandAll();
            *//*for (int i = 0; i < dt1.Rows.Count; i++)
            {
                int prjcode = int.Parse(dt1.Rows[i][1].ToString());
                TreeNode f1 = treeView1.Nodes.Add(dt1.Rows[i][0].ToString());
                string sql2 = "select dataname from project_data where prjcode =" + prjcode;
                DataTable dt2 = DataAccess.Get_DataTable(sql2, "prj");
                for (int j = 0; j < dt2.Rows.Count; j++)
                {
                    f1.Nodes.Add(dt2.Rows[j][0].ToString());
                }
            }*//*
         string sql2 = "select datatype,dataname from project_data where prjcode =" + prjcode;
         DataTable dt2 = DataAccess.Get_DataTable(sql2, "prj_data");
            for (int i = 0; i < dt2.Rows.Count; i++)
            {
                if (dt2.Rows[i][0].ToString() == "图片")
                {
                   TreeNode node =  photoNode.Nodes.Add(dt2.Rows[i][1].ToString());
                    node.ImageIndex = 1;
                }
                if (dt2.Rows[i][0].ToString() == "文档")
                {
                    TreeNode node = txtNode.Nodes.Add(dt2.Rows[i][1].ToString());
                    node.ImageIndex = 2;
                }
                if (dt2.Rows[i][0].ToString() == "矢量数据")
                {
                    TreeNode node = VectorNode.Nodes.Add(dt2.Rows[i][1].ToString());
                    node.ImageIndex = 3;
                }
                if (dt2.Rows[i][0].ToString() == "三维数据")
                {
                    TreeNode node = ThreeDNode.Nodes.Add(dt2.Rows[i][1].ToString());
                    node.ImageIndex = 4;
                }

            }*/
            //

            string sql = "select prjname from project where prjcode =" + prjcode;
            DataTable dt = DataAccess.Get_DataTable(sql, "prj");
            TreeNode node1 = treeView1.Nodes.Add(dt.Rows[0][0].ToString());//项目结点
            node1.ImageIndex = 5;
            string sql1 = "select subname,subcode from subgeo where prjcode=" + prjcode;
            DataTable dt1 = DataAccess.Get_DataTable(sql1, "prj");
            //MessageBox.Show(dt1.Rows[0][0].ToString());
            for (int j = 0; j < dt1.Rows.Count; j++)
            {
                //MessageBox.Show(dt1.Rows[j][0].ToString());
                TreeNode node2 = node1.Nodes.Add(dt1.Rows[j][0].ToString());//子区结点
                node2.ImageIndex = 13;
                string sql2 = "select dataname,datacode from data where subcode=" + dt1.Rows[j][1].ToString();
                DataTable dt2 = DataAccess.Get_DataTable(sql2, "prj");
                for (int k = 0; k < dt2.Rows.Count; k++)
                {
                    TreeNode node3 = node2.Nodes.Add(dt2.Rows[k][0].ToString());//资料结点
                    node3.ImageIndex = 14;
                    string sql3 = "select appendname,appendtype from append where datacode=" + dt2.Rows[k][1].ToString();
                    DataTable dt3 = DataAccess.Get_DataTable(sql3, "prj");
                    DataTable dt3_1 = dt3.DefaultView.ToTable(true, new string[] { "appendtype" });
                    //MessageBox.Show(dt3_1.Rows[1][0].ToString());
                    for (int n = 0; n < dt3_1.Rows.Count; n++)
                    {
                        if(dt3_1.Rows[n][0].ToString() == "图片")
                        {
                            photoNode = node3.Nodes.Add("图片");
                            photoNode.ImageIndex = 10;
                        }
                        if (dt3_1.Rows[n][0].ToString() == "文档")
                        {
                            txtNode = node3.Nodes.Add("文档");
                            txtNode.ImageIndex = 9;
                        }
                        if (dt3_1.Rows[n][0].ToString() == "矢量数据")
                        {
                            VectorNode = node3.Nodes.Add("矢量数据");
                            VectorNode.ImageIndex = 11;
                        }
                        if (dt3_1.Rows[n][0].ToString() == "三维模型")
                        {
                            ThreeDNode = node3.Nodes.Add("三维模型");
                            ThreeDNode.ImageIndex = 12;
                        }
                        if (dt3_1.Rows[n][0].ToString() == "栅格数据")
                        {
                            TifNode = node3.Nodes.Add("栅格数据");
                            TifNode.ImageIndex = 15;
                        }
                        if (dt3_1.Rows[n][0].ToString() == "剖面图")
                        {
                            SectionalPicNode = node3.Nodes.Add("剖面图");
                            SectionalPicNode.ImageIndex = 16;
                        }
                    }
                    for (int m = 0; m < dt3.Rows.Count; m++)
                    {
                        if (dt3.Rows[m][1].ToString() == "图片")
                        {
                            TreeNode node = photoNode.Nodes.Add(dt3.Rows[m][0].ToString());
                            node.ImageIndex = 1;
                        }
                        if (dt3.Rows[m][1].ToString() == "文档")
                        {
                            TreeNode node = txtNode.Nodes.Add(dt3.Rows[m][0].ToString());
                            node.ImageIndex = 2;
                        }
                        if (dt3.Rows[m][1].ToString() == "矢量数据")
                        {
                            TreeNode node = VectorNode.Nodes.Add(dt3.Rows[m][0].ToString());
                            node.ImageIndex = 3;
                        }
                        if (dt3.Rows[m][1].ToString() == "三维模型")
                        {
                            TreeNode node = ThreeDNode.Nodes.Add(dt3.Rows[m][0].ToString());
                            node.ImageIndex = 4;
                        }
                        if (dt3.Rows[m][1].ToString() == "栅格数据")
                        {
                            TreeNode node = TifNode.Nodes.Add(dt3.Rows[m][0].ToString());
                            node.ImageIndex = 18;
                        }
                        if (dt3.Rows[m][1].ToString() == "剖面图")
                        {
                            TreeNode node = SectionalPicNode.Nodes.Add(dt3.Rows[m][0].ToString());
                            node.ImageIndex = 17;
                        }
                    }

                }
            }


        }

        private void ribbonButton4_Click(object sender, EventArgs e)
        {
            Form_OpenPrj openPrj = new Form_OpenPrj(this);

            openPrj.Show();
        }

        private void treeView1_BeforeSelect(object sender, TreeViewCancelEventArgs e)
        {
            if (e.Action == TreeViewAction.Unknown)
                e.Cancel = true;
        }

        private void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if(e.Node.Level == 1)
            {
                string subname = e.Node.Text;
                string sql = "select subcode,subdescribe from subgeo where subname = '" + subname + "'";
                DataTable dt1 = DataAccess.Get_DataTable(sql, "getsubcode");
                string subgeodescribe = dt1.Rows[0][1].ToString();
                //MessageBox.Show(dt1.Rows[0][0].ToString()); 
                int subcode = Convert.ToInt32(dt1.Rows[0][0]);
                sql = "select x,y from subgeo_domain where subcode=" + subcode;
                DataTable dt2 = DataAccess.Get_DataTable(sql, "getxy");
                CreateShpFile(dt2, subname, subgeodescribe);
                string filepath = Application.StartupPath.ToString() + "\\Temp";
                string fileName = subname+".shp";
                axMapControl1.AddShapeFile(filepath, fileName);
            }
            if (e.Node.Level == 4)
            {
                string appendname = e.Node.Text;
                string sql = "select appendtype,appenddata from append where appendname = '" + appendname + "'";
                DataTable dt = DataAccess.Get_DataTable(sql, "ms");
                byte[] bt = (byte[])dt.Rows[0][1];
                //this.ms = new MemoryStream(bt);

                
                if (dt.Rows[0][0].ToString() == "文档")
                {
                    string sql2 = "select append_x,append_y from append where appendname = '" + appendname + "'";
                    DataTable dt2 = DataAccess.Get_DataTable(sql2, "xy");
                    CreatPointshp(dt2, appendname);
                    string filepath = Application.StartupPath.ToString() + "\\Temp";
                    string fileName = appendname + ".shp";
                    axMapControl1.AddShapeFile(filepath, fileName);
                    // 创建符号
                    IPictureMarkerSymbol pPictureMarkerSymbol = new PictureMarkerSymbol();
                    pPictureMarkerSymbol.Angle = 0;
                    string s = Application.StartupPath.ToString() + "\\pic\\文档.png";
                    pPictureMarkerSymbol.CreateMarkerSymbolFromFile(esriIPictureType.esriIPicturePNG, s);
                    pPictureMarkerSymbol.Size = 50;

                    // 设置符号
                    int index = GetLayerIndexByName(appendname);
                    //MessageBox.Show(index.ToString());
                    IGeoFeatureLayer pGeoFeatureLayer = axMapControl1.get_Layer(index) as IGeoFeatureLayer;
                    IFeatureRenderer pFeatureRenderer = pGeoFeatureLayer.Renderer;
                    ISimpleRenderer pSimpleRenderer = pFeatureRenderer as ISimpleRenderer;
                    pSimpleRenderer.Symbol = pPictureMarkerSymbol as ESRI.ArcGIS.Display.ISymbol;

                    // 刷新地图
                    axMapControl1.Refresh();
                    axTOCControl1.Update();

                    /*Form_PdfShow pdf = new Form_PdfShow(ms);
                    pdf.Show();*/

                }
                if (dt.Rows[0][0].ToString() == "图片")
                {
                    string sql2 = "select append_x,append_y from append where appendname = '" + appendname + "'";
                    DataTable dt2 = DataAccess.Get_DataTable(sql2, "xy");
                    CreatPointshp(dt2, appendname);
                    string filepath = Application.StartupPath.ToString() + "\\Temp";
                    string fileName = appendname + ".shp";
                    axMapControl1.AddShapeFile(filepath, fileName);
                    // 创建符号
                    IPictureMarkerSymbol pPictureMarkerSymbol = new PictureMarkerSymbol();
                    pPictureMarkerSymbol.Angle = 0;
                    string s = Application.StartupPath.ToString() + "\\pic\\图片.png";
                    pPictureMarkerSymbol.CreateMarkerSymbolFromFile(esriIPictureType.esriIPicturePNG, s);
                    pPictureMarkerSymbol.Size = 50;

                    // 设置符号
                    int index = GetLayerIndexByName(appendname);
                    //MessageBox.Show(index.ToString());
                    IGeoFeatureLayer pGeoFeatureLayer = axMapControl1.get_Layer(index) as IGeoFeatureLayer;
                    IFeatureRenderer pFeatureRenderer = pGeoFeatureLayer.Renderer;
                    ISimpleRenderer pSimpleRenderer = pFeatureRenderer as ISimpleRenderer;
                    pSimpleRenderer.Symbol = pPictureMarkerSymbol as ESRI.ArcGIS.Display.ISymbol;

                    // 刷新地图
                    axMapControl1.Refresh();
                    axTOCControl1.Update();

                   /* Form_PhotoShow pdf = new Form_PhotoShow(ms);
                    pdf.Show();*/
                }
                if (dt.Rows[0][0].ToString() == "三维模型")
                {
                    string sql2 = "select append_x,append_y from append where appendname = '" + appendname + "'";
                    DataTable dt2 = DataAccess.Get_DataTable(sql2, "xy");
                    CreatPointshp(dt2, appendname);
                    string filepath = Application.StartupPath.ToString() + "\\Temp";
                    string fileName = appendname + ".shp";
                    axMapControl1.AddShapeFile(filepath, fileName);
                    // 创建符号
                    IPictureMarkerSymbol pPictureMarkerSymbol = new PictureMarkerSymbol();
                    pPictureMarkerSymbol.Angle = 0;
                    string s = Application.StartupPath.ToString() + "\\pic\\三维.png";
                    pPictureMarkerSymbol.CreateMarkerSymbolFromFile(esriIPictureType.esriIPicturePNG, s);
                    pPictureMarkerSymbol.Size = 50;

                    // 设置符号
                    int index = GetLayerIndexByName(appendname);
                    //MessageBox.Show(index.ToString());
                    IGeoFeatureLayer pGeoFeatureLayer = axMapControl1.get_Layer(index) as IGeoFeatureLayer;
                    IFeatureRenderer pFeatureRenderer = pGeoFeatureLayer.Renderer;
                    ISimpleRenderer pSimpleRenderer = pFeatureRenderer as ISimpleRenderer;
                    pSimpleRenderer.Symbol = pPictureMarkerSymbol as ESRI.ArcGIS.Display.ISymbol;

                    // 刷新地图
                    axMapControl1.Refresh();
                    axTOCControl1.Update();

                    //vtkshow2(ms);
                }
                if (dt.Rows[0][0].ToString() == "剖面图")
                {
                    string sql2 = "select append_x,append_y from append where appendname = '" + appendname + "'";
                    DataTable dt2 = DataAccess.Get_DataTable(sql2, "xy");
                    CreatPointshp(dt2, appendname);
                    string filepath = Application.StartupPath.ToString() + "\\Temp";
                    string fileName = appendname + ".shp";
                    axMapControl1.AddShapeFile(filepath, fileName);
                    // 创建符号
                    IPictureMarkerSymbol pPictureMarkerSymbol = new PictureMarkerSymbol();
                    pPictureMarkerSymbol.Angle = 0;
                    string s = Application.StartupPath.ToString() + "\\pic\\剖面图.png";
                    pPictureMarkerSymbol.CreateMarkerSymbolFromFile(esriIPictureType.esriIPicturePNG, s);
                    pPictureMarkerSymbol.Size = 50;

                    // 设置符号
                    int index = GetLayerIndexByName(appendname);
                    //MessageBox.Show(index.ToString());
                    IGeoFeatureLayer pGeoFeatureLayer = axMapControl1.get_Layer(index) as IGeoFeatureLayer;
                    IFeatureRenderer pFeatureRenderer = pGeoFeatureLayer.Renderer;
                    ISimpleRenderer pSimpleRenderer = pFeatureRenderer as ISimpleRenderer;
                    pSimpleRenderer.Symbol = pPictureMarkerSymbol as ESRI.ArcGIS.Display.ISymbol;

                    // 刷新地图
                    axMapControl1.Refresh();
                    axTOCControl1.Update();

                    //vtkshow2(ms);
                }
                if (dt.Rows[0][0].ToString() == "矢量数据")
                {
                    string path = Application.StartupPath.ToString() + "\\Temp\\"+appendname+".zip";
                    //Globale.filepath = path;
                    ByteHelper.ByteFile(bt, path);
                    ByteHelper.ZipTOFile(path);
                    string shppath = path + ".extract\\"+ appendname+".shp";
                    //Globale.filepath2 = shppath;
                    //MessageBox.Show(shppath);
                    string shppath1 = System.IO.Path.GetDirectoryName(shppath);
                    //MessageBox.Show(shppath1);

                    IPropertySet ps = new PropertySet();
                    IWorkspaceFactory pFact;
                    IWorkspace pWorkspace;
                    
                    ps.SetProperty("DATABASE", shppath1);
                    pFact = new ShapefileWorkspaceFactory();
                    pWorkspace = pFact.Open(ps, 0);
                    //IDataset dataset = pWorkspace as IDataset;
                    IFeatureWorkspace pFW = (IFeatureWorkspace)pWorkspace;
                    //MessageBox.Show(shppath);
                    IFeatureClass pFC = pFW.OpenFeatureClass(System.IO.Path.GetFileNameWithoutExtension(shppath));
                    IFeatureLayer pFL = new FeatureLayer();
                    pFL.FeatureClass = pFC;
                    pFL.Name = pFC.AliasName;
                    axMapControl1.AddLayer(pFL);
                    IWorkspaceFactoryLockControl ipWsFactoryLock = (IWorkspaceFactoryLockControl)pFact;
                    if (ipWsFactoryLock.SchemaLockingEnabled)
                    {
                        ipWsFactoryLock.DisableSchemaLocking();
                    }

                    /*System.Runtime.InteropServices.Marshal.ReleaseComObject(pFW);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(pFW);*/

                }
                if (dt.Rows[0][0].ToString() == "栅格数据")
                {
                    string path = Application.StartupPath.ToString() + "\\Temp\\" + appendname + ".tif";
                    ByteHelper.ByteFile(bt, path);
                    AddRasterFile(path);
                }

            }
        }

        private void AddRasterFile(string filePath)
        {
            IWorkspaceFactory pWorkspaceFactory = new RasterWorkspaceFactory();
            IWorkspace pWorkspace = pWorkspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(filePath), 0);
            IRasterWorkspace pRasterWorkspace = pWorkspace as IRasterWorkspace;
            //IRasterDataset pRasterDataset = pRasterWorkspace.OpenRasterDataset(System.IO.Path.GetFileName(filePath));
            IRasterDataset pRasterDataset = pRasterWorkspace.OpenRasterDataset(System.IO.Path.GetFileName(filePath));
            // 创建金字塔
            IRasterPyramid pRasterPyramid = pRasterDataset as IRasterPyramid;
            if (!pRasterPyramid.Present)
            {
                pRasterPyramid.Create();
            }

            // 栅格图层
            IRasterLayer pRasterLayer = new RasterLayer();
            pRasterLayer.CreateFromDataset(pRasterDataset);
            ILayer pLayer = pRasterLayer as ILayer;

            // 刷新地图
            axMapControl1.AddLayer(pLayer, 0);
            axMapControl1.Refresh();
            /*IWorkspaceFactoryLockControl ipWsFactoryLock = (IWorkspaceFactoryLockControl)pWorkspaceFactory;
            if (ipWsFactoryLock.SchemaLockingEnabled)
            {
                ipWsFactoryLock.DisableSchemaLocking();
            }*/
        }

        private void AddRasterDataset(string directory)
        {
            IWorkspaceFactory pWorkspaceFactory = new FileGDBWorkspaceFactory();
            IWorkspace pWorkspace = pWorkspaceFactory.OpenFromFile(directory, 0);
            IRasterWorkspaceEx pRasterWorkspaceEx = pWorkspace as IRasterWorkspaceEx;

            // 获取栅格数据集
            IEnumDataset pEnumDataset = pWorkspace.get_Datasets(esriDatasetType.esriDTRasterDataset);
            pEnumDataset.Reset();
            IDataset pDataset = pEnumDataset.Next();

            // 遍历数据集
            while (pDataset != null)
            {
                // 创建金字塔
                IRasterDataset pRasterDataset = pRasterWorkspaceEx.OpenRasterDataset(pDataset.Name);
                IRasterPyramid pRasterPyramid = pRasterDataset as IRasterPyramid;
                if (!pRasterPyramid.Present)
                {
                    pRasterPyramid.Create();
                }

                // 栅格图层
                IRasterLayer pRasterLayer = new RasterLayer();
                pRasterLayer.CreateFromDataset(pRasterDataset);

                // 刷新视图
                axMapControl1.AddLayer(pRasterLayer, 0);
                axMapControl1.Refresh();

                // 下一数据集
                pDataset = pEnumDataset.Next();
            }

        }



        private void axTOCControl1_OnMouseUp(object sender, ITOCControlEvents_OnMouseUpEvent e)
        {
            esriTOCControlItem item = esriTOCControlItem.esriTOCControlItemNone;
            IBasicMap map = null;
            m_layer = null;
            object other = null;
            object index = null;
            axTOCControl1.HitTest(e.x, e.y, ref item, ref map, ref m_layer, ref other, ref index);//判断所点击的类型

            if (e.button == 2)
            {
                if (item == esriTOCControlItem.esriTOCControlItemLayer)
                {
                    axMapControl1.CustomProperty = m_layer;

                    IToolbarMenu menu = new ToolbarMenu();
                    menu.SetHook(axMapControl1.Object);

                    menu.AddItem(new ControlsFeatureSelectionToolbar());
                    menu.AddSubMenu(new ControlsFeatureSelectionMenu());
                    menu.AddItem(new ControlsRemoveLayer());
                    menu.AddItem(new ControlsRenderLayer());

                    menu.PopupMenu(e.x, e.y, axTOCControl1.hWnd);

                }

            }




            esriTOCControlItem pItem = esriTOCControlItem.esriTOCControlItemNone;
            IBasicMap pBasMap = null;
            ILayer pLayer = null;
            object pOther = null;
            object pIndex = null;
            if (e.button == 1)
            {
                axTOCControl1.HitTest(e.x, e.y, ref pItem, ref pBasMap, ref pLayer, ref pOther, ref pIndex);
                if (pMoveLayer != pLayer)//如果是原图层则不用操作
                {
                    IMap pMap = axMapControl1.Map;
                    ILayer pTempLayer;
                    for (int i = 0; i < pMap.LayerCount; i++)
                    {
                        pTempLayer = pMap.get_Layer(i);
                        if (pTempLayer == pLayer)//获取移动后的图层索引
                            toIndex = i;
                    }
                    pMap.MoveLayer(pMoveLayer, toIndex);
                    axMapControl1.ActiveView.Refresh();
                    axTOCControl1.Update();
                }
            }

        }

        private void vtkShow(String s)
        {
            vtkPoints Points = vtkPoints.New();


            String path = s;
            double x, y, z;
            foreach (String str in System.IO.File.ReadAllLines(path))
            {

                if (str != null)
                {
                    string[] strArray = str.Split(',');
                    double[] doubleArray = System.Array.ConvertAll(strArray, double.Parse);
                    x = doubleArray[0];
                    y = doubleArray[1];
                    z = doubleArray[2];
                    /*Console.WriteLine(x);
                    Console.WriteLine(y);
                    Console.WriteLine(z);*/

                    Points.InsertNextPoint(x, y, z);      //_加入点信息  

                }
            }


            vtkPolyData polydata = vtkPolyData.New();
            polydata.SetPoints(Points);

            vtkVertexGlyphFilter glyphFilter = vtkVertexGlyphFilter.New();
            glyphFilter.SetInputConnection(polydata.GetProducerPort());
            glyphFilter.Update();

            vtkPolyDataMapper mapper = vtkPolyDataMapper.New();
            mapper.SetInput(glyphFilter.GetOutput());
            mapper.ScalarVisibilityOff();

            vtkActor actor = vtkActor.New();
            actor.SetMapper(mapper);
            actor.GetProperty().SetPointSize(1);
            actor.GetProperty().SetColor(205, 173, 0);

            vtkRenderer renderer = vtkRenderer.New();
            renderer.AddActor(actor);
            //renderer.SetViewport(0, 0.0, 0, 0);
            renderer.SetBackground(255, 255, 255); // Background color green



            vtkSurfaceReconstructionFilter surf = vtkSurfaceReconstructionFilter.New();
            surf.SetInput(polydata);

            vtkContourFilter contour = vtkContourFilter.New();
            contour.SetInputConnection(surf.GetOutputPort());
            contour.SetValue(0, 0.0);

            vtkPolyDataMapper surfMapper = vtkPolyDataMapper.New();
            surfMapper.SetInput(contour.GetOutput());

            vtkActor surfActor = vtkActor.New();
            surfActor.SetMapper(surfMapper);
            surfActor.GetProperty().SetColor(0, 0, 0);

            vtkRenderer surfRenderer = vtkRenderer.New();
            surfRenderer.AddActor(surfActor);
            surfRenderer.SetBackground(255, 255, 255);



            vtkRenderWindow renderWindow = RWControl.RenderWindow;
            renderWindow.AddRenderer(renderer);
            renderWindow.AddRenderer(surfRenderer);


            vtkRenderWindowInteractor renderWindowInteractor = vtkRenderWindowInteractor.New();
            renderWindowInteractor.SetRenderWindow(renderWindow);

            renderWindow.Render();
        }

        private void axTOCControl1_OnMouseDown(object sender, ITOCControlEvents_OnMouseDownEvent e)
        {
            esriTOCControlItem item = esriTOCControlItem.esriTOCControlItemNone;
            IBasicMap map = null;
            m_layer = null;
            object other = null;
            object index = null;
            axTOCControl1.HitTest(e.x, e.y, ref item, ref map, ref m_layer, ref other, ref index);//判断所点击的类型

            esriTOCControlItem pItem = esriTOCControlItem.esriTOCControlItemNone;
            IBasicMap pBasMap = null;
            ILayer pLayer = null;
            object pOther = null;
            object pIndex = null;

            if (e.button == 1 && m_layer != null)
            {
                if (m_layer is IFeatureLayer)
                {
                    //dataGridView1.Rows.Clear();
                    IFeatureLayer pFeaturelayer = (IFeatureLayer)m_layer;
                    IFeatureCursor pFC = pFeaturelayer.Search(null, true);
                    IFeature pFeature = pFC.NextFeature();
                    int j = 0;
                    DataTable dt = new DataTable();
                    for (int i = 0; i < pFeaturelayer.FeatureClass.Fields.FieldCount; i++)
                    {
                        IField pField = pFeaturelayer.FeatureClass.Fields.get_Field(i);
                        DataColumn pDC = new DataColumn(pField.Name);
                        if (pField.Name == pFeaturelayer.FeatureClass.OIDFieldName) pDC.Unique = true;
                        pDC.AllowDBNull = pField.IsNullable;
                        pDC.Caption = pField.AliasName;
                        pDC.DefaultValue = pField.DefaultValue;
                        if (pField.VarType == 8) pDC.MaxLength = pField.Length;
                        dt.Columns.Add(pDC);
                    }
                    while (pFeature != null)
                    {
                        DataRow dr = dt.NewRow();
                        for (int i = 0; i < pFeaturelayer.FeatureClass.Fields.FieldCount; i++)
                        {
                            if (pFeature.Fields.get_Field(i).Type == esriFieldType.esriFieldTypeGeometry)
                                dr[i] = pFeature.Shape.GeometryType.ToString();
                            else
                                dr[i] = pFeature.get_Value(i);
                        }
                        dt.Rows.Add(dr);
                        pFeature = pFC.NextFeature();
                        j++;
                    }
                    dataGridView1.DataSource = dt;

                }

                axTOCControl1.HitTest(e.x, e.y, ref pItem, ref pBasMap, ref pLayer, ref pOther, ref pIndex);

                if (pItem == esriTOCControlItem.esriTOCControlItemLayer)
                {
                    if (pLayer is IAnnotationSublayer) return;//如果是注记图层则返回
                    else
                        pMoveLayer = pLayer;

                }
            }
        }

        private void axMapControl1_OnMouseMove(object sender, IMapControlEvents2_OnMouseMoveEvent e)
        {
            // 显示当前坐标
            this.toolStripStatusLabel1.Text = "比例尺 1:" + ((long)this.axMapControl1.MapScale).ToString();
            // this.barCoorTxt.Text = "当前坐标 X=" + e.mapX.ToString() + "Y=" + e.mapY.ToString() + "" + this.axMapControl1.MapUnits;

            sMapUnits = GetMapUnit(axMapControl1.Map.MapUnits);
            barCoorTxt.Text = String.Format("当前坐标：X = {0:#.###} Y = {1:#.###} {2}", e.mapX, e.mapY, sMapUnits);
            pMovePt = (axMapControl1.Map as IActiveView).ScreenDisplay.DisplayTransformation.ToMapPoint(e.x, e.y);
        }
        private string GetMapUnit(esriUnits _esriMapUnit)//返回这个单位
        {
            string sMapUnits = string.Empty;
            switch (_esriMapUnit)
            {
                case esriUnits.esriCentimeters:
                    sMapUnits = "厘米";
                    break;
                case esriUnits.esriDecimalDegrees:
                    sMapUnits = "十进制";
                    break;
                case esriUnits.esriDecimeters:
                    sMapUnits = "分米";
                    break;
                case esriUnits.esriFeet:
                    sMapUnits = "尺";
                    break;
                case esriUnits.esriInches:
                    sMapUnits = "英寸";
                    break;
                case esriUnits.esriKilometers:
                    sMapUnits = "千米";
                    break;
                case esriUnits.esriMeters:
                    sMapUnits = "米";
                    break;
                case esriUnits.esriMiles:
                    sMapUnits = "英里";
                    break;
                case esriUnits.esriMillimeters:
                    sMapUnits = "毫米";
                    break;
                case esriUnits.esriNauticalMiles:
                    sMapUnits = "海里";
                    break;
                case esriUnits.esriPoints:
                    sMapUnits = "点";
                    break;
                case esriUnits.esriUnitsLast:
                    sMapUnits = "UnitsLast";
                    break;
                case esriUnits.esriUnknownUnits:
                    sMapUnits = "未知单位";
                    break;
                case esriUnits.esriYards:
                    sMapUnits = "码";
                    break;
                default:
                    break;
            }
            return sMapUnits;
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            ICommand command = new ControlsOpenDocCommand();
            command.OnCreate(axMapControl1.Object);
            command.OnClick();
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            ICommand command = new ControlsSaveAsDocCommand();
            command.OnCreate(axMapControl1.Object);
            command.OnClick();
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            axMapControl1.Extent = axMapControl1.FullExtent;
            axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, axMapControl1.ActiveView.Extent);
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            
            ICommand command = new ControlsMapZoomOutTool();
            command.OnCreate(this.axMapControl1.Object);
            this.axMapControl1.CurrentTool = command  as ITool;
        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            
            ICommand command = new ControlsMapZoomInTool();
            command.OnCreate(this.axMapControl1.Object);
            this.axMapControl1.CurrentTool = command as ITool;
        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            //ITool tool = new ControlsMapPanToolClass();
            ICommand command = new ControlsMapPanTool();
            command.OnCreate(this.axMapControl1.Object);
            this.axMapControl1.CurrentTool = command as ITool   ;
        }

        private void toolStripButton7_Click(object sender, EventArgs e)
        {
            // tool = ;
            ICommand command = new ControlsMapIdentifyTool();
            command.OnCreate(this.axMapControl1.Object);
            this.axMapControl1.CurrentTool = command as ITool;
        }

        public void createBookmark(string sBookmarkName)
        {
            //通过 IAOIBookmark接口创建一个变量，类型为AOIBookmark，用于保存当前地图
            IAOIBookmark aoiBookmark = new AOIBookmark();
            if (aoiBookmark != null)
            {
                aoiBookmark.Location = axMapControl1.ActiveView.Extent;
                aoiBookmark.Name = sBookmarkName;
            }
            //通过IMapBookmarks接口访问当前地图，并向地图中加入新建书签
            IMapBookmarks bookmarks = axMapControl1.Map as IMapBookmarks;
            if (bookmarks != null)
            {
                bookmarks.AddBookmark(aoiBookmark);
            }
            //将新建书签名加入组合框中，用于之后调用对应书签
            cbBookmarkList.Items.Add(aoiBookmark.Name);
        }

        private void cbBookmarkList_SelectedIndexChanged(object sender, EventArgs e)
        {
            //访问地图所包含的书签，并获取书签序列
            IMapBookmarks bookmarks = axMapControl1.Map as IMapBookmarks;
            IEnumSpatialBookmark enumspatialBookmark = bookmarks.Bookmarks;
            //对地图所包含的书签进行遍历，获取与组合框所选项名称相符的书签
            enumspatialBookmark.Reset();
            ISpatialBookmark spatialBookmark = enumspatialBookmark.Next();
            while (enumspatialBookmark != null)
            {
                if (cbBookmarkList.SelectedItem.ToString() == spatialBookmark.Name)
                {
                    spatialBookmark.ZoomTo((IMap)axMapControl1.ActiveView);
                    axMapControl1.ActiveView.Refresh();
                    break;
                }
                spatialBookmark = enumspatialBookmark.Next();
            }
        }

        private void toolStripButton8_Click(object sender, EventArgs e)
        {
            Form_BookMark f = new Form_BookMark(this);
            f.Show();
        }

        private void toolStripButton9_Click(object sender, EventArgs e)
        {
            ICommand command = new ControlsAddDataCommand();
            command.OnCreate(axMapControl1.Object);
            command.OnClick();
        }
        private void CreateShpFile(DataTable dt, string shpname,string describe)
        {
            IWorkspaceFactory pWF = new ShapefileWorkspaceFactoryClass();
            //这个例子将shp所在文件夹定死了，在项目中会根据参数来设置。
            //当所选的文件夹不存在的时候程序会报错。
            IFeatureWorkspace pFWs = pWF.OpenFromFile(Application.StartupPath.ToString() + "\\Temp", 0) as IFeatureWorkspace;

            IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass();
            IObjectClassDescription ocDescription = fcDescription as IObjectClassDescription;



            IFields pFields = new ESRI.ArcGIS.Geodatabase.Fields();
            IFieldsEdit pFieldsEdit = pFields as IFieldsEdit;
            IField pField = new ESRI.ArcGIS.Geodatabase.Field();
            IFieldEdit pFieldEdit = pField as IFieldEdit;

            //================这个部分是最重要的========================
            //这段代码确定了这个shp文件的集合类型（polygon、polyline、point）
            //这个字段的名称一定要设置，如果没有设置程序会出错。
            //但是这个shp文件几何字段的名称并不是设置的这个。
            IGeometryDef pGeometryDef = new GeometryDefClass();
            IGeometryDefEdit pGeometryDefEdit = pGeometryDef as IGeometryDefEdit;
            pGeometryDefEdit.SpatialReference_2 = GetSpatialReference(Application.StartupPath.ToString() + "\\Default.prj") as ISpatialReference;
            pGeometryDefEdit.GeometryType_2 = ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolygon;
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry;
            pFieldEdit.GeometryDef_2 = pGeometryDef;
            pFieldEdit.Name_2 = "shape";
            pFieldsEdit.AddField(pField);
            //============================================================

            //==============添加OID字段=========================
            pField = new ESRI.ArcGIS.Geodatabase.Field();
            pFieldEdit = pField as IFieldEdit;
            pFieldEdit.Name_2 = "OID";
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID;
            pFieldsEdit.AddField(pField);

            //==============添加WaHa字段，没有实际意义，只是为了测试========
            pField = new ESRI.ArcGIS.Geodatabase.Field();
            pFieldEdit = pField as IFieldEdit;
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
            pFieldEdit.Name_2 = "描述";
            pFieldEdit.Length_2 = 100;
            pFieldsEdit.AddField(pField);

            //=============创建shp文件===================
            string shpname1 = shpname + ".shp";
            IFeatureClass pFC = pFWs.CreateFeatureClass(shpname1, pFields, null, null, esriFeatureType.esriFTSimple, "Shape", "");

            //=============在shp文件中创建新记录=========
            IFeature pFeature = pFC.CreateFeature();


            //=========根据别人给的参数（这里是自己定死的）建立一个polygon字段值
            object missing = Type.Missing;
            IPointCollection pPc = new ESRI.ArcGIS.Geometry.Polygon();
            IPoint point = new ESRI.ArcGIS.Geometry.Point();
            /*point.X = 0;
            point.Y = 0;
            pPc.AddPoint(point, ref missing, ref missing);

            point = new ESRI.ArcGIS.Geometry.Point();
            point.X = 10;
            point.Y = 0;
            pPc.AddPoint(point, ref missing, ref missing);

            point = new ESRI.ArcGIS.Geometry.Point();
            point.X = 10;
            point.Y = 10;
            pPc.AddPoint(point, ref missing, ref missing);

            point = new ESRI.ArcGIS.Geometry.Point();
            point.X = 0;
            point.Y = 10;
            pPc.AddPoint(point, ref missing, ref missing);*/
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                point = new ESRI.ArcGIS.Geometry.Point();
                point.X = Convert.ToDouble(dt.Rows[i][0]);
                point.Y = Convert.ToDouble(dt.Rows[i][1]);
                pPc.AddPoint(point, ref missing, ref missing);
            }

            point = new ESRI.ArcGIS.Geometry.Point();
            point.X = Convert.ToDouble(dt.Rows[0][0]);
            point.Y = Convert.ToDouble(dt.Rows[0][1]);
            pPc.AddPoint(point, ref missing, ref missing);

            pFeature.Shape = pPc as IGeometry;
            //对创建的这一行记录中的WaHa字段进行赋值（值为abc）
            pFeature.set_Value(pFeature.Fields.FindField("描述"), describe);
            //保存该记录
            pFeature.Store();
            IWorkspaceFactoryLockControl ipWsFactoryLock = (IWorkspaceFactoryLockControl)pWF;
            if (ipWsFactoryLock.SchemaLockingEnabled)
            {
                ipWsFactoryLock.DisableSchemaLocking();
            }
        }

        private void CreatPointshp(DataTable dt, string shpname)
        {
            IWorkspaceFactory pWF = new ShapefileWorkspaceFactoryClass();
            //这个例子将shp所在文件夹定死了，在项目中会根据参数来设置。
            //当所选的文件夹不存在的时候程序会报错。
            IFeatureWorkspace pFWs = pWF.OpenFromFile(Application.StartupPath.ToString() + "\\Temp", 0) as IFeatureWorkspace;

            IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass();
            IObjectClassDescription ocDescription = fcDescription as IObjectClassDescription;



            IFields pFields = new ESRI.ArcGIS.Geodatabase.Fields();
            IFieldsEdit pFieldsEdit = pFields as IFieldsEdit;
            IField pField = new ESRI.ArcGIS.Geodatabase.Field();
            IFieldEdit pFieldEdit = pField as IFieldEdit;
            //================这个部分是最重要的========================
            //这段代码确定了这个shp文件的集合类型（polygon、polyline、point）
            //这个字段的名称一定要设置，如果没有设置程序会出错。
            //但是这个shp文件几何字段的名称并不是设置的这个。
            IGeometryDef pGeometryDef = new GeometryDefClass();
            IGeometryDefEdit pGeometryDefEdit = pGeometryDef as IGeometryDefEdit;
            pGeometryDefEdit.SpatialReference_2 = GetSpatialReference(Application.StartupPath.ToString()+ "\\Default.prj") as ISpatialReference;
            pGeometryDefEdit.GeometryType_2 = ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPoint;
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry;
            pFieldEdit.GeometryDef_2 = pGeometryDef;
            pFieldEdit.Name_2 = "shape";
            pFieldsEdit.AddField(pField);
            //============================================================

            //==============添加OID字段=========================
            pField = new ESRI.ArcGIS.Geodatabase.Field();
            pFieldEdit = pField as IFieldEdit;
            pFieldEdit.Name_2 = "OID";
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID;
            pFieldsEdit.AddField(pField);

            //==============添加WaHa字段，没有实际意义，只是为了测试========
            pField = new ESRI.ArcGIS.Geodatabase.Field();
            pFieldEdit = pField as IFieldEdit;
            pFieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
            pFieldEdit.Name_2 = "描述";
            pFieldEdit.Length_2 = 100;
            pFieldsEdit.AddField(pField);

            //=============创建shp文件===================
            string shpname1 = shpname + ".shp";
            IFeatureClass pFC = pFWs.CreateFeatureClass(shpname1, pFields, null, null, esriFeatureType.esriFTSimple, "Shape", "");

            //=============在shp文件中创建新记录=========
            IFeature pFeature = pFC.CreateFeature();



            object missing = Type.Missing;
            //IPointCollection pPc = new ESRI.ArcGIS.Geometry.Point();
            IPoint point = new ESRI.ArcGIS.Geometry.Point();

            point = new ESRI.ArcGIS.Geometry.Point();
            point.X = Convert.ToDouble(dt.Rows[0][0]);
            point.Y = Convert.ToDouble(dt.Rows[0][1]);
            //pPc.AddPoint(point, ref missing, ref missing);

            pFeature.Shape = point;
            //对创建的这一行记录中的WaHa字段进行赋值（值为abc）
            pFeature.set_Value(pFeature.Fields.FindField("描述"), "为该区该资料的附件");
            //保存该记录
            pFeature.Store();
            IWorkspaceFactoryLockControl ipWsFactoryLock = (IWorkspaceFactoryLockControl)pWF;
            if (ipWsFactoryLock.SchemaLockingEnabled)
            {
                ipWsFactoryLock.DisableSchemaLocking();
            }
        }



















        //VTK
        // VTK
        public float[] getLimit(List<Zone> zonelist, String var)
        {
            float max = float.MinValue, min = float.MaxValue;
            for (int i = 0; i < zonelist.Count(); i++)
            {
                Dictionary<string, List<float>> map = zonelist[i].getVarMap();
                List<float> list = map[var];
                float maxf = list.Max();
                float minf = list.Min();
                if (maxf > max)
                    max = maxf;
                if (minf < min)
                    min = minf;
            }
            return new float[] { max, min };
        }


        void updata(string varnow, List<Zone> zonelist)
        {
            float[] varlimit = getLimit(zonelist, varnow);
            this.RWControl.RenderWindow.GetRenderers().GetFirstRenderer().RemoveAllViewProps();
            vtkColorTransferFunction tempFunction = GetContinus16ColorLevel(varlimit[1], varlimit[0]);
            for (int i = 0; i < zonelist.Count(); i++)
            {
                vtkDataSetMapper mapper = DrawPointCloud(zonelist[i], varnow, isQUJian);
                //设置色阶            
                mapper.SetLookupTable(tempFunction);
                mapper.Update();
                vtkActor pointCloudActor = new vtkActor();
                pointCloudActor.SetMapper(mapper);
                pointCloudActor.GetProperty().SetPointSize(5);
                //pointCloudActor.GetProperty().SetInterpolationToFlat();
                //pointCloudActor.GetProperty().EdgeVisibilityOn();
                pointCloudActor.GetProperty().SetEdgeColor(0, 0, 0);
                pointCloudActor.GetProperty().SetRepresentationToSurface();
                //pointCloudActor.GetProperty().SetColor(255, 255, 255);
                //pointCloudActor.GetProperty().SetAmbient(1.0);
                pointCloudActor.GetProperty().SetDiffuse(0.0);
                pointCloudActor.GetProperty().SetSpecular(0.0);
                pointCloudActor.AddPosition(3.75, 1.25, 0);
                this.RWControl.RenderWindow.GetRenderers().GetFirstRenderer().AddActor(pointCloudActor);

            }

            vtkScalarBarActor barActor = new vtkScalarBarActor();
            barActor.SetNumberOfLabels(4);
            barActor.SetWidth(0.1);
            barActor.SetTextPositionToPrecedeScalarBar();
            barActor.GetTitleTextProperty().SetColor(0, 0, 0);
            barActor.GetLabelTextProperty().SetColor(0, 0, 0);
            barActor.GetTitleTextProperty().SetShadow(0);
            barActor.GetLabelTextProperty().SetShadow(0);
            barActor.SetHeight(0.6);
            barActor.SetPosition(0.88, 0.4);
            barActor.SetLookupTable(tempFunction);
            barActor.SetLabelFormat("%.2e");

            this.RWControl.RenderWindow.GetRenderers().GetFirstRenderer().AddActor(barActor);
            this.RWControl.Refresh();
            //vtkActor pointCloudActor = new vtkActor();
            //pointCloudActor.SetMapper(mapper);
            //pointCloudActor.GetProperty().SetPointSize(5);
            //显示色阶

        }
        List<Zone> zonelist;

        private void ComboBox1_SelectedValueChanged(object sender, EventArgs e)
        {
            varNow = comboBox1.SelectedItem.ToString();
            if (!isQUJian)
            {
                if (zonelist.Count == 0)
                    zonelist = initdata(contourZoneChange, false);
                updata(varNow, zonelist);
            }
            else
            {


                updataQuJian();
            }
        }

        public List<Zone> initdata(ContourZone contourZoneChange, bool boll)
        {
            contourZoneChange.zones.Clear();
            returnNum = 0;//初始化
            for (int i = 0; i < contourZoneChange.getValLimits().Count(); i++)
            {
                object[] data = new object[] { contourZoneChange, 50f, i, zoneData.varDatas, this, boll };
                DataFactory datafactory = new DataFactory();
                datafactory.setData(data);
                ThreadStart threadStart = new ThreadStart(datafactory.getPointsAndCell);//多线程读取解析
                Thread thread = new Thread(threadStart);
                thread.Start();
            }
            while (true)
            {
                if (returnNum == 6)
                    break;
            }

            return contourZoneChange.zones;
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void DrawAxes()
        {
            if (null == marker)
            {
                vtkAxesActor axes = new vtkAxesActor();
                axes.SetShaftTypeToLine();
                axes.SetXAxisLabelText("x");
                axes.SetYAxisLabelText("y");
                axes.SetZAxisLabelText("z");
                axes.SetTotalLength(1.6, 1.6, 1.6);
                marker = new vtkOrientationMarkerWidget();
                vtkRenderWindowInteractor iren = this.RWControl.RenderWindow.GetInteractor();
                marker.SetInteractor(iren);
                marker.SetOrientationMarker(axes);
                marker.SetViewport(-0.2, -0.2, 0.3, 0.3);
                marker.SetEnabled(1);
                marker.SetInteractive(0);
            }
        }

        /// <summary>
        /// 绘制点云图  从数据中析出网格数据
        /// </summary>
        private vtkDataSetMapper DrawPointCloud(Zone zone, String varnow, bool isQUJIAN)
        {
            vtkPoints tempPoints = new vtkPoints();
            vtkFloatArray tempArray = new vtkFloatArray();
            vtkUnstructuredGrid tempGrid = new vtkUnstructuredGrid();
            List<float> listTV;
            if (isQUJIAN)
            {
                for (int i = 0; i < zoneData.centerX_LS.Count; i++)
                {
                    tempPoints.InsertNextPoint(zoneData.centerX_LS[i], zoneData.centerY_LS[i], zoneData.centerZ_LS[i]);
                }
                List<Face> listf = zone.getFaces();

                for (int i = 0; i < listf.Count(); i++)
                {

                    Face face = listf[i];
                    vtkIdList facearr = new vtkIdList();
                    int[] facechid = face.getFaces();
                    for (int k = 0; k < facechid.Count(); k++)
                    {
                        facearr.InsertNextId(facechid[k]);
                    }
                    tempGrid.InsertNextCell(7, facearr);

                }


                listTV = zoneData.varDatas[varnow];

                tempArray.SetNumberOfComponents(1);
                tempArray.SetNumberOfTuples(listTV.Count());
                for (int i = 0; i < listTV.Count(); i++)//面ID  面值   
                    tempArray.SetTuple1(i, listTV[i]);
            }
            else
            {
                List<P3D> list = zone.getPoints();
                for (int i = 0; i < list.Count(); i++)
                {
                    P3D p3d = list[i];
                    tempPoints.InsertNextPoint(p3d.getX(), p3d.getY(), p3d.getZ());
                }
                List<Face> listf = zone.getFaces();

                for (int i = 0; i < listf.Count(); i++)
                {


                    Face face = listf[i];
                    vtkIdList facearr = new vtkIdList();
                    int[] facechid = face.getFaces();
                    for (int k = 0; k < facechid.Count(); k++)
                    {
                        facearr.InsertNextId(facechid[k]);
                    }
                    tempGrid.InsertNextCell(7, facearr);

                }

                listTV = zone.getVarMap()[varnow];

                tempArray.SetNumberOfComponents(1);
                tempArray.SetNumberOfTuples(listTV.Count());
                for (int i = 0; i < listTV.Count(); i++)//面ID  面值   
                    tempArray.SetTuple1(i, listTV[i]);
            }


            tempGrid.SetPoints(tempPoints);
            tempGrid.GetPointData().SetScalars(tempArray);
            vtkDataSetMapper mapper = new vtkDataSetMapper();
            mapper.SetInput(tempGrid);
            mapper.SetScalarRange(listTV.Max(), listTV.Min());
            mapper.InterpolateScalarsBeforeMappingOn();
            mapper.SetScalarModeToUsePointData();
            return mapper;
        }
        /// <summary>
        /// 得到连续的颜色映射表
        /// </summary>
        /// <param name="minValue"></param>
        /// <param name="maxValue"></param>
        /// <returns></returns>
        private vtkColorTransferFunction GetContinus32ColorLevel(double minValue, double maxValue)
        {      //R(red)红、G(green)绿、B(blue)蓝
            vtkColorTransferFunction lut = new vtkColorTransferFunction();
            double tempStep = (maxValue - minValue) / 32;
            lut.AddRGBPoint(minValue + tempStep * 0.5, 37 / 255.0, 0, 0);
            lut.AddRGBPoint(minValue + tempStep * 1.5, 50 / 255.0, 0, 0);
            lut.AddRGBPoint(minValue + tempStep * 2.5, 61 / 255.0, 0, 0);
            lut.AddRGBPoint(minValue + tempStep * 3.5, 89 / 255.0, 0, 0);
            lut.AddRGBPoint(minValue + tempStep * 4.5, 108 / 255.0, 0, 0);
            lut.AddRGBPoint(minValue + tempStep * 5.5, 128 / 255.0, 0, 0);
            lut.AddRGBPoint(minValue + tempStep * 6.5, 150 / 255.0, 0, 0);
            lut.AddRGBPoint(minValue + tempStep * 7.5, 174 / 255.0, 0, 0);
            lut.AddRGBPoint(minValue + tempStep * 8.5, 199 / 255.0, 0, 0);
            lut.AddRGBPoint(minValue + tempStep * 9.5, 223 / 255.0, 1 / 255.0, 0);
            lut.AddRGBPoint(minValue + tempStep * 10.5, 248 / 255.0, 0 / 255.0, 0);
            lut.AddRGBPoint(minValue + tempStep * 11.5, 1, 15 / 255.0, 0);
            lut.AddRGBPoint(minValue + tempStep * 12.5, 1, 40 / 255.0, 0);
            lut.AddRGBPoint(minValue + tempStep * 13.5, 1, 61 / 255.0, 0);
            lut.AddRGBPoint(minValue + tempStep * 14.5, 1, 86 / 255.0, 0);
            lut.AddRGBPoint(minValue + tempStep * 15.5, 1, 109 / 255.0, 3 / 255.0);
            lut.AddRGBPoint(minValue + tempStep * 16.5, 1, 130 / 255.0, 1 / 255.0);
            lut.AddRGBPoint(minValue + tempStep * 17.5, 1, 148 / 255.0, 0 / 255.0);
            lut.AddRGBPoint(minValue + tempStep * 18.5, 1, 166 / 255.0, 0 / 255.0);
            lut.AddRGBPoint(minValue + tempStep * 19.5, 1, 174 / 255.0, 0 / 255.0);
            lut.AddRGBPoint(minValue + tempStep * 20.5, 1, 200 / 255.0, 1 / 255.0);
            lut.AddRGBPoint(minValue + tempStep * 21.5, 1, 218 / 255.0, 0 / 255.0);
            lut.AddRGBPoint(minValue + tempStep * 22.5, 1, 226 / 255.0, 20 / 255.0);
            lut.AddRGBPoint(minValue + tempStep * 23.5, 1, 232 / 255.0, 38 / 255.0);
            lut.AddRGBPoint(minValue + tempStep * 24.5, 1, 239 / 255.0, 58 / 255.0);
            lut.AddRGBPoint(minValue + tempStep * 25.5, 1, 245 / 255.0, 80 / 255.0);
            lut.AddRGBPoint(minValue + tempStep * 26.5, 1, 252 / 255.0, 101 / 255.0);
            lut.AddRGBPoint(minValue + tempStep * 27.5, 1, 255 / 255.0, 123 / 255.0);
            lut.AddRGBPoint(minValue + tempStep * 28.5, 1, 255 / 255.0, 151 / 255.0);
            lut.AddRGBPoint(minValue + tempStep * 29.5, 1, 255 / 255.0, 177 / 255.0);
            lut.AddRGBPoint(minValue + tempStep * 30.5, 1, 255 / 255.0, 205 / 255.0);
            lut.AddRGBPoint(minValue + tempStep * 31.5, 1, 255 / 255.0, 232 / 255.0);
            return lut;
        }
        /// <summary>
        /// 得到连续的颜色映射表
        /// </summary>
        /// <param name="minValue"></param>
        /// <param name="maxValue"></param>
        /// <returns></returns>    
        private vtkColorTransferFunction GetContinus16ColorLevel(double minValue, double maxValue)
        {
            vtkColorTransferFunction lut = new vtkColorTransferFunction();
            double tempStep = (maxValue - minValue) / 13;
            lut.AddRGBPoint(minValue + tempStep * 0.0, 0, 0, 1);
            lut.AddRGBPoint(minValue + tempStep * 1.0, 0, 0, 1);
            lut.AddRGBPoint(minValue + tempStep * 2.0, 0, 0.38, 0.62);
            lut.AddRGBPoint(minValue + tempStep * 3.0, 0, 0.38, 0.62);
            lut.AddRGBPoint(minValue + tempStep * 4.0, 0, 0.76, 0.24);
            lut.AddRGBPoint(minValue + tempStep * 5.0, 0, 0.76, 0.24);
            lut.AddRGBPoint(minValue + tempStep * 6.0, 1, 1, 0);
            lut.AddRGBPoint(minValue + tempStep * 6.0, 1, 1, 0);
            lut.AddRGBPoint(minValue + tempStep * 7.0, 0.38, 0.62, 0);
            lut.AddRGBPoint(minValue + tempStep * 8.0, 0.38, 0.62, 0);
            lut.AddRGBPoint(minValue + tempStep * 9.0, 0.76, 0.24, 0);
            lut.AddRGBPoint(minValue + tempStep * 10.0, 0.76, 0.24, 0);
            lut.AddRGBPoint(minValue + tempStep * 11.0, 1, 0, 0);
            lut.AddRGBPoint(minValue + tempStep * 12.0, 1, 0, 0);

            //lut.AddRGBPoint(minValue + tempStep * 13.5, 1, 1, 124 / 255.0);
            //lut.AddRGBPoint(minValue + tempStep * 14.5, 1, 1, 178 / 255.0);
            //lut.AddRGBPoint(minValue + tempStep * 15.5, 1, 1, 237 / 255.0);
            //lut.AddRGBPoint(minValue + tempStep * 16.5, 1, 1, 1); 
            return lut;
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            isQUJian = checkBox1.Checked;
        }

        private void min_TextChanged(object sender, EventArgs e)
        {
            if (min.Text.Trim() != null && !max.Text.Equals(""))
            {
                varlimitData[0] = Convert.ToSingle(min.Text);
            }
        }

        private void max_TextChanged(object sender, EventArgs e)
        {
            if (max.Text.Trim() != null && !max.Text.Equals(""))
            {
                varlimitData[1] = Convert.ToSingle(max.Text);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            varNow = comboBox1.SelectedItem.ToString();
            if (!isQUJian)
            {
                if (zonelist.Count == 0)
                    zonelist = initdata(contourZoneChange, false);
                updata(comboBox1.SelectedItem.ToString(), zonelist);
            }

            else
            {
                updataQuJian();
            }
        }
        /**
         * 区间更新
         * */
        public void updataQuJian()
        {
            if (min.Text.Trim() != null && !max.Text.Equals(""))
            {
                varlimitData[0] = Convert.ToSingle(min.Text);
            }
            else
            {
                varlimitData[0] = float.MinValue;
            }

            if (max.Text.Trim() != null && !max.Text.Equals(""))
            {
                varlimitData[1] = Convert.ToSingle(max.Text);
            }
            else
            {
                varlimitData[1] = float.MaxValue;
            }
            zonelist.Clear();
            List<Zone> zon = initTiWangGe(true);
            updata(varNow, zon);
        }

        /**
       * 体网格数据
       * */
        public List<Zone> initTiWangGe(bool boll)
        {

            ContourZone contourZoneChange = new ContourZone(zoneData);
            object[] data = new object[] { contourZoneChange, 50f, 0, zoneData.varDatas, this, boll };
            DataFactory datafactory = new DataFactory();
            datafactory.setData(data);
            datafactory.getPointsAndCell();


            return contourZoneChange.zones;
        }

        private void vtkshow2(MemoryStream ms)
        {
            List<P3D> list = new List<P3D>();
            list.Add(new P3D(1, 1, 1));
            list.Insert(0, new P3D(2, 2, 2));

            vtkRenderer render = this.RWControl.RenderWindow.GetRenderers().GetFirstRenderer();
            render.GradientBackgroundOn();
            render.SetBackground( 255.0,  255.0, 255.0);
            render.SetBackground2(255.0,  255.0, 255.0);

            //绘制坐标系
            DrawAxes();
            //读取数据
            zoneData = readerFile.reader(ms); 
            //zoneData = readerFile.reader("newdata0.csv"); 
            contourZoneChange = new ContourZone(zoneData);
            zonelist = initdata(contourZoneChange, false);
            String varnow = zoneData.varNames[0];
            for (int i = 0; i < zoneData.varNames.Count(); i++)
            {
                comboBox1.Items.Add(zoneData.varNames[i]);
            }
            comboBox1.SelectedIndex = 0;
            updata(varnow, zonelist);

            LoadingHelper.CloseForm();
            //设置默认摄像机
            this.RWControl.Show();
            this.RWControl.RenderWindow.GetRenderers().GetFirstRenderer().GetActiveCamera().ParallelProjectionOn();
            this.RWControl.RenderWindow.GetRenderers().GetFirstRenderer().ResetCamera();
            this.RWControl.Refresh();

            comboBox1.SelectedValueChanged += ComboBox1_SelectedValueChanged;
        }
        //VTK



        private void ribbonButton5_Click(object sender, EventArgs e)
        {
            Form_NewPrj newprj = new Form_NewPrj();
            newprj.Show();
        }

        private void ribbonButton6_Click(object sender, EventArgs e)
        {
            Form_UpdatePrj upprj = new Form_UpdatePrj();
            upprj.Show();
        }

        private void ribbonButton1_Click(object sender, EventArgs e)
        {
            Form_AddData adddata = new Form_AddData();
            adddata.Show();
        }

        private void ribbonButton9_Click(object sender, EventArgs e)
        {
            Form_NewSub newsub = new Form_NewSub();
            newsub.Show();
        }

        private void ribbonButton10_Click(object sender, EventArgs e)
        {
            Form_EditSub editsub = new Form_EditSub();
            editsub.Show();
        }

        private int GetLayerIndexByName(string strLyrName)
        {
            ILayer pLayer = null;
            bool bFindLayer = false;
            int index = 0;
            for (int i = 0; i < axMapControl1.Map.LayerCount; i++)
            {
                pLayer = axMapControl1.Map.get_Layer(i);
                if (pLayer is IGroupLayer || pLayer is ICompositeLayer)
                {
                    ICompositeLayer pComLyr = pLayer as ICompositeLayer;
                    for (int j = 0; j < pComLyr.Count; j++)
                    {
                        pLayer = pComLyr.get_Layer(j);
                        if (pLayer.Name.Equals(strLyrName))
                        {
                            bFindLayer = true;
                            break;
                        }
                        else
                        {
                            pLayer = null;
                        }
                    }
                }
                else
                {
                    if (pLayer.Name == strLyrName)
                    {
                        bFindLayer = true;
                    }
                    else
                    {
                        pLayer = null;
                    }
                }
                if (bFindLayer)
                {
                    break;
                }
                index = i;
            }
            return index;
        }

        public static ISpatialReference GetSpatialReference(string filePath)
        {
            ISpatialReferenceFactory pSpatialReferenceFactory = new SpatialReferenceEnvironment();
            ISpatialReference pSpatialReference = pSpatialReferenceFactory.CreateESRISpatialReferenceFromPRJFile(filePath);
            return pSpatialReference;
        }

        private void axTOCControl1_OnDoubleClick(object sender, ITOCControlEvents_OnDoubleClickEvent e)
        {
            if (e.button == 1)
            {
                esriTOCControlItem Item = new esriTOCControlItem();
                IBasicMap pMap = new MapClass();
                ILayer pLayer = new FeatureLayerClass();
                object pOther = new object();
                object pIndex = new object();
                this.axTOCControl1.HitTest(e.x, e.y, ref Item, ref pMap, ref pLayer, ref pOther, ref pIndex);
                this.LayerName = pLayer.Name;
            }
            
            string sql = "select appendtype,appenddata from append where appendname = '" + LayerName + "'";
            DataTable dt = DataAccess.Get_DataTable(sql, "ms");
            if (dt.Rows.Count != 0)
            {
                byte[] bt = (byte[])dt.Rows[0][1];
                MemoryStream ms = new MemoryStream(bt);
                if (dt.Rows[0][0].ToString() == "文档")
                {
                    Form_PdfShow pdf = new Form_PdfShow(ms);
                    pdf.Show();
                }
                if (dt.Rows[0][0].ToString() == "图片")
                {
                    Form_PhotoShow pic = new Form_PhotoShow(ms);
                    pic.Show();
                }
                if (dt.Rows[0][0].ToString() == "三维模型")
                {
                    skinGroupBox2.Visible = true;
                    vtkshow2(ms);
                }
                if (dt.Rows[0][0].ToString() == "剖面图")
                {
                    string path = Application.StartupPath.ToString() + "\\Temp\\" + LayerName + ".zip";
                    //Globale.filepath = path;
                    ByteHelper.ByteFile(bt, path);
                    ByteHelper.ZipTOFile(path);
                    string dicpath = path + ".extract\\" + LayerName;
                    this.dicpath = dicpath;
                    SectionPlanShow(dicpath);
                    //MessageBox.Show(dicpath + ".jpg");
                }
            }
        }
        public void SectionPlanShow(string dicpath)
        {
            
            //cube
            vtkCubeSource cube = vtkCubeSource.New();
            vtkPolyDataMapper cubeMapper = vtkPolyDataMapper.New();
            cubeMapper.SetInputConnection(cube.GetOutputPort());
            vtkActor cubeActor = vtkActor.New();
            cubeActor.SetMapper(cubeMapper);
            cube.SetXLength(80);
            cube.SetZLength(80);
            cube.SetYLength(11);
            cubeActor.GetProperty().SetOpacity(0.2);




            vtkRenderer renderer = vtkRenderer.New();
            renderer.AddActor(cubeActor);

            //text
            for (int i = 5; i <= 80; i = i + 5)
            {
                vtkVectorText textz = vtkVectorText.New();
                textz.SetText(i.ToString());

                vtkPolyDataMapper textmapperz = vtkPolyDataMapper.New();
                textmapperz.SetInputConnection(textz.GetOutputPort());

                vtkFollower followz = vtkFollower.New();
                followz.SetMapper(textmapperz);
                followz.SetScale(1, 1, 1);
                followz.AddPosition(-42, -5, -40 + i);
                followz.GetProperty().SetColor(255, 255, 255);
                renderer.AddActor(followz);
            }
            for (int i = 0; i <= 10; i = i + 5)
            {
                vtkVectorText textz = vtkVectorText.New();
                textz.SetText(i.ToString());

                vtkPolyDataMapper textmapperz = vtkPolyDataMapper.New();
                textmapperz.SetInputConnection(textz.GetOutputPort());

                vtkFollower followz = vtkFollower.New();
                followz.SetMapper(textmapperz);
                followz.SetScale(1, 1, 1);
                followz.AddPosition(-42, -5 + i, -40);
                followz.GetProperty().SetColor(255, 255, 255);
                renderer.AddActor(followz);
            }

            for (int i = 5; i <= 80; i = i + 5)
            {
                vtkVectorText textz = vtkVectorText.New();
                textz.SetText(i.ToString());

                vtkPolyDataMapper textmapperz = vtkPolyDataMapper.New();
                textmapperz.SetInputConnection(textz.GetOutputPort());

                vtkFollower followz = vtkFollower.New();
                followz.SetMapper(textmapperz);
                followz.SetScale(1, 1, 1);
                followz.AddPosition(-40 + i, -5, -42);
                followz.GetProperty().SetColor(255, 255, 255);
                renderer.AddActor(followz);
            }

            //图片
            for (int i = 1; i <= 8; i++)
            {
                vtkJPEGReader Readerpic = vtkJPEGReader.New();
                Readerpic.SetFileName(dicpath+ i + ".jpg");

                vtkTexture texturepic = vtkTexture.New();
                texturepic.SetInputConnection(Readerpic.GetOutputPort());

                string sql = "select x,y,z from plane where id="+i;
                DataTable dt = DataAccess.Get_DataTable(sql, "plane");
                int center_x = int.Parse(dt.Rows[0][0].ToString());
                int center_y = int.Parse(dt.Rows[0][1].ToString());
                int center_z = int.Parse(dt.Rows[0][2].ToString());
                int origin_x = int.Parse(dt.Rows[1][0].ToString());
                int origin_y = int.Parse(dt.Rows[1][1].ToString());
                int origin_z = int.Parse(dt.Rows[1][2].ToString());
                int point1_x = int.Parse(dt.Rows[2][0].ToString());
                int point1_y = int.Parse(dt.Rows[2][1].ToString());
                int point1_z = int.Parse(dt.Rows[2][2].ToString());
                int point2_x = int.Parse(dt.Rows[3][0].ToString());
                int point2_y = int.Parse(dt.Rows[3][1].ToString());
                int point2_z = int.Parse(dt.Rows[3][2].ToString());


                vtkPlaneSource planepic = vtkPlaneSource.New();
                planepic.SetCenter(center_x, center_y, center_z);//设置平面中心点坐标
                planepic.SetOrigin(origin_x, origin_y, origin_z);//设置平面起点坐标，一般为平面左下角
                planepic.SetPoint1(point1_x, point1_y, point1_z);//设置平面第一条轴的长度
                planepic.SetPoint2(point2_x, point2_y, point2_z);//设置平面第二条轴的长度
                                                        //plane1.SetNormal(1, 1, 1);//设置平面的法向量
                planepic.Update();
                vtkPolyDataMapper mapperpic = vtkPolyDataMapper.New();
                mapperpic.SetInputConnection(planepic.GetOutputPort());

                vtkActor actorpic = vtkActor.New();
                actorpic.SetMapper(mapperpic);
                actorpic.SetTexture(texturepic);

                renderer.AddActor(actorpic);
            }

            vtkRenderWindow win = RWControl.RenderWindow;
            win.AddRenderer(renderer);
            /*renderer.SetBackground(255.0, 255.0, 255.0);
            renderer.SetBackground2(255.0, 255.0, 255.0);*/

            win.Render();

            //坐标系
            vtkAxesActor axes = new vtkAxesActor();
            axes.SetShaftTypeToLine();
            axes.SetXAxisLabelText("x");
            axes.SetYAxisLabelText("y");
            axes.SetZAxisLabelText("z");
            axes.SetTotalLength(1.6, 1.6, 1.6);
            marker = new vtkOrientationMarkerWidget();
            vtkRenderWindowInteractor iren = win.GetInteractor();
            marker.SetInteractor(iren);
            marker.SetOrientationMarker(axes);
            marker.SetViewport(-0.2, -0.2, 0.3, 0.3);
            marker.SetEnabled(1);
            marker.SetInteractive(0);

            vtkRenderWindowInteractor interactor = vtkRenderWindowInteractor.New();
            interactor.Start();
            this.RWControl.Show();
            this.skinGroupBox3.Visible = true;
        }
        private void toolStripButton10_Click(object sender, EventArgs e)
        {
            if (this.axMapControl1.Map!= null)
            {
                Form_LayerLabel fl = new Form_LayerLabel(this.axMapControl1.Map);
                fl.Show();
            }
            else
            {
                MessageBoxEx.Show("请先导入图层");
            }
        }

        private void ribbonButton11_Click(object sender, EventArgs e)
        {
            skinGroupBox1.Visible = true;
            
        }

        private void skinRadioButton1_CheckedChanged(object sender, EventArgs e)
        {
            if (skinRadioButton1.Checked )
            {
                IMapServerRESTLayer mapServerRESTLayer = new MapServerRESTLayerClass();
                mapServerRESTLayer.Connect("http://cache1.arcgisonline.cn/arcgis/rest/services/ChinaOnlineStreetPurplishBlue/MapServer");
                ILayer layer = mapServerRESTLayer as ILayer;
                layer.Name = "深色底图";
                axMapControl1.AddLayer(layer);

                IEnvelope pEnvelope = (IEnvelope)axMapControl1.ActiveView.FullExtent;
                IPoint point = new PointClass();
                point.Y = 3742885.122;
                point.X = 13057436.401;
                point.PutCoords(point.X, point.Y);
                pEnvelope.Expand(0.0001, 0.0001, true);
                pEnvelope.CenterAt(point);
                axMapControl1.ActiveView.Extent = pEnvelope;
                axMapControl1.ActiveView.Refresh();

                axMapControl1.Refresh();

            }
        }

        private void skinRadioButton2_CheckedChanged(object sender, EventArgs e)
        {
            if (skinRadioButton2.Checked)
            {
                IMapServerRESTLayer mapServerRESTLayer = new MapServerRESTLayerClass();
                mapServerRESTLayer.Connect("http://cache1.arcgisonline.cn/arcgis/rest/services/ChinaOnlineStreetGray/MapServer");
                ILayer layer = mapServerRESTLayer as ILayer;
                layer.Name = "灰色底图";
                axMapControl1.AddLayer(layer);

                IEnvelope pEnvelope = (IEnvelope)axMapControl1.ActiveView.FullExtent;
                IPoint point = new PointClass();
                point.Y = 3742885.122;
                point.X = 13057436.401;
                point.PutCoords(point.X, point.Y);
                pEnvelope.Expand(0.0001, 0.0001, true);
                pEnvelope.CenterAt(point);
                axMapControl1.ActiveView.Extent = pEnvelope;
                axMapControl1.ActiveView.Refresh();

                axMapControl1.Refresh();

            }

        }

        private void skinRadioButton3_CheckedChanged(object sender, EventArgs e)
        {
            if (skinRadioButton3.Checked)
            {
                IMapServerRESTLayer mapServerRESTLayer = new MapServerRESTLayerClass();
                mapServerRESTLayer.Connect("http://cache1.arcgisonline.cn/arcgis/rest/services/ChinaOnlineStreetWarm/MapServer");
                ILayer layer = mapServerRESTLayer as ILayer;
                layer.Name = "暖色底图";
                axMapControl1.AddLayer(layer);

                IEnvelope pEnvelope = (IEnvelope)axMapControl1.ActiveView.FullExtent;
                IPoint point = new PointClass();
                point.Y = 3742885.122;
                point.X = 13057436.401;
                point.PutCoords(point.X, point.Y);
                pEnvelope.Expand(0.0001, 0.0001, true);
                pEnvelope.CenterAt(point);
                axMapControl1.ActiveView.Extent = pEnvelope;
                axMapControl1.ActiveView.Refresh();

                axMapControl1.Refresh();

            }
        }

        private void skinRadioButton4_CheckedChanged(object sender, EventArgs e)
        {
            if (skinRadioButton4.Checked)
            {
                MapServerRESTLayerClass mapServerRESTLayer = new MapServerRESTLayerClass();
                mapServerRESTLayer.Connect("http://cache1.arcgisonline.cn/ArcGIS/rest/services/ChinaOnlineCommunity/MapServer");
                mapServerRESTLayer.Name = "基础底图";
                ILayer layer = mapServerRESTLayer as ILayer;
                axMapControl1.AddLayer(layer);
                IEnvelope pEnvelope = (IEnvelope)axMapControl1.ActiveView.FullExtent;
                IPoint point = new PointClass();
                point.Y = 3742885.122;
                point.X = 13057436.401;
                point.PutCoords(point.X, point.Y);
                pEnvelope.Expand(0.0001, 0.0001, true);
                pEnvelope.CenterAt(point);
                axMapControl1.ActiveView.Extent = pEnvelope;
                axMapControl1.ActiveView.Refresh();
                axMapControl1.Refresh();
            }
        }

        private void ribbonButton8_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog dialog = new OpenFileDialog())
            {
                dialog.Multiselect = false;
                dialog.Filter = "矢量数据|*.shp;*.shp";
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    string path = System.IO.Path.GetFullPath(dialog.FileName);
                    //MessageBox.Show(path);
                    string path_shp2 = System.IO.Path.GetDirectoryName(path);
                    IPropertySet ps = new PropertySet();
                    IWorkspaceFactory pFact;
                    IWorkspace pWorkspace;
                    ps.SetProperty("DATABASE", path_shp2);
                    pFact = new ShapefileWorkspaceFactory();
                    pWorkspace = pFact.Open(ps, 0);
                    IFeatureWorkspace pFW = (IFeatureWorkspace)pWorkspace;
                    IFeatureClass pFC = pFW.OpenFeatureClass(System.IO.Path.GetFileNameWithoutExtension(path));
                    IFeatureLayer pFL = new FeatureLayer();
                    pFL.FeatureClass = pFC;
                    pFL.Name = pFC.AliasName;
                    axMapControl1.AddLayer(pFL);
                    
                }
                    
            }
        }

        private void ribbonButton12_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = "选择栅格文件";
            openFileDialog.Filter = "TIFF(*.tif)|*.tif";
            openFileDialog.RestoreDirectory = true;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                AddRasterFile(openFileDialog.FileName);
            }

        }

        private void ribbonButton13_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            folderBrowserDialog.Description = "请选择文件地理数据库";
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                if (!folderBrowserDialog.SelectedPath.EndsWith(".gdb"))
                {
                    MessageBox.Show("请选择文件地理数据库", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    AddRasterDataset(folderBrowserDialog.SelectedPath);
                }
            }
        }

        private void ribbonButton2_Click(object sender, EventArgs e)
        {
            Form_OutputData fm = new Form_OutputData();
            fm.Show();
        }

        private void ribbonButton3_Click(object sender, EventArgs e)
        {
            Form_DataEdit fm = new Form_DataEdit();
            fm.Show();
        }

        private void ribbonButton14_Click(object sender, EventArgs e)
        {
            
            if(panel1.Visible==false)
            {
                panel1.Visible = true;
                Usertable();
            }
        }

        private void ribbonButton14_DoubleClick(object sender, EventArgs e)
        {
            if (panel1.Visible == true)
            {
                panel1.Visible = false;
            }
        }
        public void Usertable()
        {
            string sql = "select user_id as '序号',user_name as '用户账户',user_password as '用户密码' from db_user";
            DataTable dt = DataAccess.Get_DataTable(sql, "user");
            skinDataGridView1.DataSource = dt;
            skinDataGridView1.Columns[0].ReadOnly = true;

        }

        private void skinButton3_Click(object sender, EventArgs e)
        {
            Form_UserEdit fm = new Form_UserEdit(this);
            fm.Show();
            
        }

        private void skinButton1_Click(object sender, EventArgs e)
        {
            string[] str = { skinDataGridView1.SelectedCells[0].Value.ToString(), skinDataGridView1.SelectedCells[1].Value.ToString(), skinDataGridView1.SelectedCells[2].Value.ToString() };
            Form_UserEdit fm = new Form_UserEdit(str,this);
            fm.Show();
        }

        private void skinButton2_Click(object sender, EventArgs e)
        {
            string sql = "delete from db_user where user_id = " + skinDataGridView1.SelectedCells[0].Value.ToString();
            DataAccess.Run_SQL(sql);
            MessageBoxEx.Show("删除成功！");
            /*this.skinDataGridView1.Rows.Clear();*/
            Usertable();
        }

        private void ribbonButton15_Click(object sender, EventArgs e)
        {
            
            // 保存文件
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Title = "导出";
            saveFileDialog.Filter = "PDF(*.pdf)|*.pdf";
            saveFileDialog.RestoreDirectory = true;
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                ExportMap(saveFileDialog.FileName, 300, 1);
            }
        }

        private void ribbonButton16_Click(object sender, EventArgs e)
        {
            
            // 保存文件
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Title = "导出";
            saveFileDialog.Filter = "TIFF(*.tif)|*.tif";
            saveFileDialog.RestoreDirectory = true;
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                ExportMap(saveFileDialog.FileName, 300, 1);
            }
        }

        private void ribbonButton17_Click(object sender, EventArgs e)
        {
           
            // 保存文件
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Title = "导出";
            saveFileDialog.Filter = "PNG(*.png)|*.png";
            saveFileDialog.RestoreDirectory = true;
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                ExportMap(saveFileDialog.FileName, 300, 1);
            }
        }

        private void ribbonButton18_Click(object sender, EventArgs e)
        {
            
            // 保存文件
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Title = "导出";
            saveFileDialog.Filter = "JPEG(*.jpeg)|*.jpeg";
            saveFileDialog.RestoreDirectory = true;
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                ExportMap(saveFileDialog.FileName, 300, 1);
            }
        }

        private void ribbonButton19_Click(object sender, EventArgs e)
        {
            
            // 保存文件
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Title = "导出";
            saveFileDialog.Filter = "SVG(*.svg)|*.svg";
            saveFileDialog.RestoreDirectory = true;
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                ExportMap(saveFileDialog.FileName, 300, 1);
            }
        }

        private void ribbonButton20_Click(object sender, EventArgs e)
        {
            
            // 保存文件
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Title = "导出";
            saveFileDialog.Filter = "BMP(*.bmp)|*.bmp";
            saveFileDialog.RestoreDirectory = true;
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                ExportMap(saveFileDialog.FileName, 300, 1);
            }
        }
        private void ExportMap(string filePath, double resolution, int resample)
        {
            IExport pExport = null;
            switch (System.IO.Path.GetExtension(filePath))
            {
                case ".pdf":
                    pExport = new ExportPDF() as IExport;
                    break;
                case ".svg":
                    pExport = new ExportSVG() as IExport;
                    break;
                case ".ai":
                    pExport = new ExportAI() as IExport;
                    break;
                case ".emf":
                    pExport = new ExportEMF() as IExport;
                    break;
                case ".eps":
                    pExport = new ExportPS() as IExport;
                    break;
                case ".bmp":
                    pExport = new ExportBMP() as IExport;
                    break;
                case ".png":
                    pExport = new ExportPNG() as IExport;
                    break;
                case ".jpeg":
                    pExport = new ExportJPEG() as IExport;
                    break;
                case ".tif":
                    pExport = new ExportTIFF() as IExport;
                    break;
                case ".gif":
                    pExport = new ExportGIF() as IExport;
                    break;
                default:
                    pExport = new ExportPDF() as IExport;
                    break;
            }

            // 设置导出路径
            pExport.ExportFileName = filePath;

            // 若导出图片，则设置重采样等级
            if (pExport is IOutputRasterSettings)
            {
                IOutputRasterSettings pOutputRasterSettings = pExport as IOutputRasterSettings;
                pOutputRasterSettings.ResampleRatio = resample;
            }

            // 若导出TIFF，则设置坐标信息
            if (pExport is IExportTIFF)
            {
                IExportTIFF pExportTIFF = pExport as IExportTIFF;
                pExportTIFF.GeoTiff = true;
                pExportTIFF.CompressionType = esriTIFFCompression.esriTIFFCompressionJPEG;
            }

            // 若导出PDF，则设置PDF格式
            if (pExport is IExportPDF)
            {
                IExportPDF pExportPDF = pExport as IExportPDF;
                pExportPDF.Compressed = true;
                pExportPDF.EmbedFonts = true;
                pExportPDF.ImageCompression = esriExportImageCompression.esriExportImageCompressionNone;
            }

            // 导出地图
            IPrintAndExport pPrintAndExport = new PrintAndExport();
            pPrintAndExport.Export(axMapControl1.ActiveView, pExport, resolution, false, null);
        }

        private void ribbonButton7_Click(object sender, EventArgs e)
        {
            treeView1.Nodes.Clear();
            TreeViewShowNodeProjectItem();
        }

        
        public void PicTable()
        {
            //datagridview展示
            int index = skinComboBox1.SelectedIndex + 1;
            string sql1 = "select pointtype,x,y,z from plane where id=" + index;
            DataTable dt0 = DataAccess.Get_DataTable(sql1, "planexyz");
            skinDataGridView2.DataSource = dt0;
        }

        private void skinButton4_Click(object sender, EventArgs e)
        {
            string[] str = { skinDataGridView2.SelectedCells[0].Value.ToString(), skinDataGridView2.SelectedCells[1].Value.ToString(),
            skinDataGridView2.SelectedCells[2].Value.ToString(),skinDataGridView2.SelectedCells[3].Value.ToString()};
            Form_PlanexyzChange fm = new Form_PlanexyzChange(str,this);
            fm.Show();
        }

        private void skinComboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            PicTable();
        }
    }
}
